package eco2automotive.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import eco2automotive.port.*;
import eco2automotive.gui.components.*;
import eco2automotive.port.ConnectionControl;
import eco2automotive.util.InitData;
import eco2automotive.data.HashParameters;
import eco2automotive.data.HashErrorCode;
import eco2automotive.util.WorkingDirectory;
import eco2automotive.util.InitData_Statics;
import eco2automotive.lang.EN;
import eco2automotive.tasks.*;
import eco2automotive.Log.TXRXInformation;
/**  
  * The ROOT WINDOW used by the app.
  * @version 1.0
 * @autor Fco. Javier Sánchez Esparza
 * 
  * @see eco2automotive.gui.components.Panel_INFOLOG
  * @see eco2automotive.gui.components.Panel_TxRx
 * @see eco2automotive.gui.components.Panel_ACTIONS
 * @see eco2automotive.gui.components.Panel_PORT_INFO
  * @see eco2automotive.gui.components.Panel_PROTOCOL
  * @see eco2automotive.gui.components.Panel_MANUAL_ACT
 * @see eco2automotive.gui.Layout_DTCs
 * @see eco2automotive.gui.Layout_MONITORING
 * @see eco2automotive.gui.Layout_DTCs
 * @see eco2automotive.gui.Layout_PORT_SELECTION
 * @see eco2automotive.tasks.Thread_app
 * @see eco2automotive.tasks.Thread_KMHRPM
 * @see eco2automotive.tasks.Thread_MONITOR

  */ 
public class eco2automotive extends JFrame{
  Connection CONN;  
  ConnectionControl connControl;
  HashErrorCode HERRORS;
  HashParameters HPARAMS;
  JLabel lblWORKDIR;      
  
  Panel_INFOLOG PANEL_INFO;
  Panel_TxRx PANEL_TXRX;   
  Panel_ACTIONS PANEL_ACTIONS;
  Panel_PORT_INFO PANEL_PORT_INFO;
  Panel_PROTOCOL PANEL_PROTOCOL;
  Panel_MANUAL_ACT PANEL_MANUAL;
  
  Layout_KMHRPM LAYOUT_KMHRPM;
  Layout_MONITORING LAYOUT_MONITORING;
  Layout_DTCs LAYOUT_DTCS;
  Layout_PORT_SELECTION PORT_SELECTION;
  
  
  Thread_app THREAD_APP; 
  Thread_KMHRPM THREAD_KMHRPM;
  Thread_MONITOR THREAD_MONITORING;
    
  TXRXInformation object_information;

   
public eco2automotive()  {	        
                super("ecC02automotive");
		setResizable(true);
                CONN=new Connection(); 
                
                PORT_SELECTION =  new Layout_PORT_SELECTION(this,CONN);     
                PORT_SELECTION.setModal(true); 
                PORT_SELECTION.setVisible(true);      
                        
                PANEL_TXRX=new Panel_TxRx();
                start_Connection();
                start_Threads();                                                
                addWindowListener(new WindowListen(this));
                
                //Working dir                
                String directory=new WorkingDirectory().workingDirectoryJar().replace('\\', '/');
                lblWORKDIR=new JLabel("(Work Directory) "+directory+"/");                                                                 
                PANEL_INFO=new Panel_INFOLOG();                   
                PANEL_PORT_INFO=new Panel_PORT_INFO(CONN);                                     
                LoadVars();          
                checkConfig();               
                PANEL_PROTOCOL=new Panel_PROTOCOL(connControl, PANEL_INFO,PANEL_TXRX);                     
                PANEL_MANUAL= new Panel_MANUAL_ACT(this);
                PANEL_ACTIONS= new Panel_ACTIONS(this);      
                do_Layout();
              
}
   /** 
     * Create a new object ConnectionControl with the Connection params
    * @thorws Exception
    */    

public void start_Connection()
{                
                try{                    
                 connControl=new ConnectionControl(CONN);
                 connControl.connect();                                     
                }catch(Exception e){
                        CONN.setPortName(null);
                }
}
    /** 
     * Status of the connection, if not connected display a new InfoAlert
 * @see eco2automotive.gui.InforAlert
    * @return true = connected, false = not connected
    */    
public boolean connectedStatus()
{
   if(this.connControl!=null)
       return true;
   else
   {
       this.PANEL_INFO.updateInfo(EN.PORT_ERROR_Not_Connected);
       new InforAlert("#ERROR",EN.PORT_ERROR_Not_Connected,1).showAlert(); 
       return false;
   }
}

 /** 
     * Create & Start the main Thread    </br>
 * @see eco2automotive.tasks.Thread_app
    */ 
public void start_Threads(){
                 THREAD_APP=new Thread_app(connControl,this.PANEL_TXRX);                 
                 THREAD_APP.start();                                                                                                                                     
}


 /** 
   * Read the voltage from the interface control</br>
   * Stop the main thread, create a new Task, and restart the main Thread_app
 * @see eco2automotive.tasks.Task_RV
    */ 

public void RVoltage(){
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_READING_VOLTAGE);                   
if(connectedStatus())
{      
this.THREAD_APP.stop_Thread();
connControl.clearFifo();
new Task_RV(this.connControl).run();                   
start_Threads();
}

}

/** 
   * Reset the trouble codes</br>
   * Stop the main thread, create a new Task, and restart the main Thread_app
 * @see eco2automotive.tasks.Task_DTCs_CLEAR
    */ 
public void ResetDTCs(){
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_DTCS_RESET);                   
if(connectedStatus())
{
this.THREAD_APP.stop_Thread();
connControl.clearFifo();
int q = new ConfirmAlert("RESET of DTCs",EN.QUICK_ACTIONS_DTCS_CONFIRM+EN.QUICK_ACTIONS_DTCS_RESET_INFO).showme();
if(q==1)
new Task_DTCs_CLEAR(this.connControl).run();
else
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_CANCELED);                   
start_Threads();
}

}

/** 
   * Search DTCs in the vehicle</br>
   * Stop the main thread, create a new Task, and restart the main Thread_app
 * @see eco2automotive.tasks.Task_DTCs
    */ 
public void QueryDTCs(){
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_QUERY_DTCS);                   
if(connectedStatus())
{          
this.THREAD_APP.stop_Thread();
LAYOUT_DTCS=new Layout_DTCs(this);
LAYOUT_DTCS.setLocationRelativeTo(null);
LAYOUT_DTCS.setVisible(true);
connControl.clearFifo();
Task_DTCs TASK_DTCs=new Task_DTCs(connControl,LAYOUT_DTCS,HERRORS);
TASK_DTCs.run();
start_Threads();
}        
}
/** 
   * Display a Layout_KMHRPM window</br>
   * Stop the main thread, create a new Thread, and restart the main Thread_app
 * @see eco2automotive.tasks.Thread_MONITOR
    */ 

public void showMonitor_KMHRPM(){                          
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_MONITOR_START);                   
if(connectedStatus())
{  
LAYOUT_KMHRPM= new Layout_KMHRPM(this);                                    
connControl.clearFifo();
THREAD_KMHRPM=new Thread_KMHRPM(connControl,LAYOUT_KMHRPM);                                        
this.THREAD_APP.stop_Thread();
this.THREAD_KMHRPM.start();       
LAYOUT_KMHRPM.setModal(true);    
LAYOUT_KMHRPM.setVisible(true); 
this.THREAD_KMHRPM.stop_Thread();       
start_Threads();
}        
}

/** 
   * Send to the interface control basic AT commands to start the communication
 * </br>
 * @see eco2automotive.tasks.Task_INIT
   */ 
public void ELMstart() {    
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_INITBUS);                   
if(connectedStatus()){  
try{                                    
new Task_INIT(connControl).run();                                                                      
PANEL_TXRX.updateTX_INFO(connControl.getTXinfo());                                
}                               
catch(Exception e){PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_ERROR);}
}
}

/** 
   * Create a new Task_ConformsTo and display the standar OBD used by the car
 * @see eco2automotive.tasks.Task_ConformsTo
   */ 

public void ConformTo(){
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_PROTOCOL_CONFORMS);                   
if(connectedStatus())
{      
connControl.clearFifo();
new Task_ConformsTo(this.connControl).run();                   
}
}
/** 
   * Send a manual command
   */ 

public void ELManual(JTextField toSend){
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_INITBUS);                   
if(connectedStatus())
    {  
    PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_MANUAL_TRY+toSend.getText());      
    try{                    
        if(toSend.getText().contentEquals("04"))
            this.ResetDTCs();
        else if (toSend.getText().contentEquals("03"))
            this.QueryDTCs();
        else connControl.TXData(toSend.getText());
    PANEL_TXRX.updateTX_INFO(connControl.getTXinfo());                    
    } 
    catch(Exception e)
    {PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_ERROR);}              
    }            
}    

/** 
   * Display a Layout_MONITORING window</br>
   * Stop the main thread, create a new Thread, and restart the main Thread_app
 * @see eco2automotive.tasks.Thread_MONITOR
    */ 

public void ELMonitorALL(){     
PANEL_INFO.updateInfo(EN.QUICK_ACTIONS_INITBUS);                   
if(connectedStatus())
{      
    LAYOUT_MONITORING=new Layout_MONITORING(this,HPARAMS);
    connControl.clearFifo();
    THREAD_MONITORING=new Thread_MONITOR(connControl,LAYOUT_MONITORING,HPARAMS);                                            
    THREAD_APP.stop_Thread();        
    THREAD_MONITORING.start();           
    LAYOUT_MONITORING.setModal(true);    
    LAYOUT_MONITORING.setVisible(true);     
    THREAD_MONITORING.stop_Thread();           
    start_Threads();    
}    
    
}

/** 
   * Load the basic data from .dat files</br>   
 * @see eco2automotive.data
    */ 

public void LoadVars(){
    String directory=new WorkingDirectory().workingDirectoryJar().replace('\\', '/');
    String source; 
    InitData ini= new InitData();
//----------------------------------------------------------------------------
    
//----------------------------------------------------------------------------    
    source=InitData_Statics.INITDATA_Directory_of_DATA_+InitData_Statics.INITDATA_NAMEof_ErrorTroubleCodes_DAT;    
    HERRORS=new HashErrorCode(ini.loadDataTroubleCodes(directory+source));    
//----------------------MOTOR PIDS ---------------------------------------------    
    source=InitData_Statics.INITDATA_Directory_of_DATA_+InitData_Statics.INITDATA_NAMEof_ParametersPIDs_DAT;    
    HPARAMS=new HashParameters(ini.loadData(directory+source));    
//----NO USED ------------------------------------------------------------------
    source=InitData_Statics.INITDATA_Directory_of_DATA_+InitData_Statics.INITDATA_NAMEof_OperationModes_DAT;
    ini.loadDataOperationModes(directory+source);        
//-----------------------------------------------------------------------
    source=InitData_Statics.INITDATA_Directory_of_DATA_+InitData_Statics.INITDATA_NAMEof_Protocols_DAT;
    ini.loadDataProtocol(directory+source);    
    this.PANEL_INFO.updateInfo(ini.getLogInformation());     
    
    }      


/** 
   * Check the port information config</br>   
    */ 


public void checkConfig(){  
    if(CONN.getNombrePuerto()!=null){
        if(CONN.getNombrePuerto().equals("<none>")||CONN.getNombrePuerto().equals("null")){            
             PANEL_INFO.updateInfo(EN.PORT_ERROR_PortNotValid);
             new InforAlert("#ERROR",EN.PORT_ERROR_Not_Connected+
                     EN.PORT_ERROR_Not_Connected_inf,1).showAlert();      
        }
        else{
          InforAlert advisory;
    advisory=new InforAlert("Wait!",EN.QUICK_ACTIONS_INITBUS_WAIT,0);                            
        advisory.showAlert();  
        PANEL_INFO.updateInfo(EN.PORT_CONNECT_Ini+CONN.getNombrePuerto()); 
        
        PANEL_INFO.updateInfo("\nName: "+CONN.getNombrePuerto()+"\nBaud: "+CONN.getBaud()+"\nDatabits: "+CONN.getDataBits()+
            "\nFlowControl: "+CONN.getFlowControlMode()+"\nParity: "+CONN.getParity()
             +"\nStop Bits: "+CONN.getStopBits()+"\nTime Out: "+CONN.getTimeOut()); 
        PANEL_INFO.updateInfo(this.connControl.getLogInformation());
        }        
    }
    else{new InforAlert("#ERROR",EN.PORT_ERROR_Not_Connected+
                     EN.PORT_ERROR_Not_Connected_inf,1).showAlert();}
    
}


public void do_Layout(){
    this.setLayout(new BorderLayout());    
    JPanel LEFT= new JPanel();
    LEFT.setLayout(new BoxLayout(LEFT, BoxLayout.Y_AXIS));    
    LEFT.add(this.PANEL_PORT_INFO);    
    LEFT.add(this.PANEL_ACTIONS);
    LEFT.add(this.PANEL_PROTOCOL);
    LEFT.add(this.PANEL_MANUAL);    
    getContentPane().add(this.PANEL_TXRX,BorderLayout.CENTER);
    getContentPane().add(LEFT,BorderLayout.WEST);       
    getContentPane().add(this.lblWORKDIR,BorderLayout.SOUTH);
    getContentPane().add(this.PANEL_INFO,BorderLayout.NORTH);

}
 public static void main(String args[]){		                                            
		eco2automotive main= new eco2automotive();	   
		main.pack();
                main.setLocationRelativeTo(null);
                main.setVisible(true);	
 //               main.setExtendedState(JFrame.MAXIMIZED_BOTH);	                                
}
       
}
class WindowListen implements WindowListener {
  Frame winRef;
  WindowListen( Frame vent ){
    this.winRef = vent;
    }
  public void windowClosed( WindowEvent evt ) {    
    this.winRef.dispose();
    System.exit( 0 );
    }

  public void windowIconified( WindowEvent evt ) {}

  public void windowOpened( WindowEvent evt ) {}

  public void windowClosing( WindowEvent evt ) {
    winRef.setVisible( false );
    this.winRef.dispose();
    System.exit( 0 );
    }

  public void windowDeiconified( WindowEvent evt ) {}

  public void windowActivated( WindowEvent evt ) {}

  public void windowDeactivated( WindowEvent evt ) {}
  }
